<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  info: ''
})
// ----
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()

/* ---- */
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'material-has-dealer/index',
    forData: {
      params: {
        'MaterialHasDealerSearch[product_name]': infoSch.value,
        // ----
        'MaterialHasDealerSearch[has_dealer_id]': logUser.id || 0,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const getNeedDate = async (curItem) => {
  await proxy.$http.get('proc/index', {
    params: { 'ProductSearch[id]': curItem.product_id }
  }).then((res) => {
    if (Number(res.items.length) > 0) curItem.goodsName = proxy.$Myfun.setText(res.items[0].name)
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    const curItem = {
      id: item.id,
      type: proxy.$Myfun.setText(item.type),
      sn: proxy.$Myfun.setText(item.has_sn),
      date: proxy.$Myfun.getDateShort(item.date),
      // ----
      product_id: item.has_product_id,
      goodsName: '产品被删'
    }
    // ----
    await getNeedDate(curItem)
    // ----
    newItems.push(curItem)
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getHeadFun(1)
}
// ----
const getHeadFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
  }
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'MaterialDown', { id: item.id, dealer_id: proxy.$route.query.dealer_id })
      break
    }
    case 2: {
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            await proxy.$http.delete('material-has-dealer/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, async (newVal, oldVal) => {
  infoSch.value = newVal.infoSch
  // --重新请求数据--
  mescroll.scrollTo(0)
  mescroll.resetUpScroll()
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  infoSch.value = forSearch.value.infoSch
})
onMounted(() => {
  // --创建MeScroll对象--
  setTimeout(() => { startMeScroll() }, 500)
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-bgCL-11 xw-flex xw-flex-align" v-if="user.info">
        <div class="TOP-msg xw-Lfg xw-flex-W1">{{user.info}}</div>
      </div>
      <!---->
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <em class="far fa-search TOP-L"></em>
          <p class="xw-flex-W1"><input class="schText" type="text" placeholder="输入产品关键词找材质书" v-model.trim="infoSch"/></p>
          <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
          <span class="TOP-btn TOP-R xw-Lfg" @click="getHeadFun(1)">搜索</span>
        </div>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-mate xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <a @click="getAuditFun(1, item)">
              <div class="LME-title xw-ellipsis" v-if="item.goodsName">{{item.goodsName}}</div>
              <div class="LME-item xw-ellipsis"><span class="xw-color-13">规格：</span>{{item.type}}</div>
              <div class="LME-item xw-ellipsis"><span class="xw-color-13">批号：</span>{{item.sn}}</div>
              <div class="LME-item xw-ellipsis"><span class="xw-color-13">日期：</span>{{item.date}}</div>
              <i class="LME-right fal fa-angle-right"></i>
            </a>
            <div class="LME-btn xw-btn xw-WBlue" @click="getAuditFun(2, item)">删除</div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.TOP-msg { padding: 0 0 0 1.4rem; font-size: 1.7rem; font-weight: bold; }
.TOP-msg:before { top: 0.2rem; bottom: 0.2rem; width: 0.8rem; background: #ffffff; }

/* ---- */
.list-mate li { position: relative; margin: 1rem 1rem 0; overflow: hidden; }
.list-mate li:nth-of-type(1) { margin-top: 0; }
.list-mate li a { display: block; position: relative; padding: 1.2rem 1rem; overflow: hidden; }
.LME-title { margin-bottom: 0.5rem; padding-right: 3rem; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; }
.LME-item { line-height: 2.5rem; }
.LME-right { position: absolute; top: 1.2rem; right: 1rem; line-height: 2.5rem; font-size: 2.4rem; color: #bbbbbb; }
.LME-btn { position: absolute; right: 1rem; bottom: 1.2rem; }
</style>